const HASH = 'hash';
const HISTORY = 'history';
let _Vue = null;

export default class VueRouter {
  static install(Vue) {
    if (this.installed) return;

    this.installed = true;
    _Vue = Vue;

    // 所有Vue实例都要获取到$router对象
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          // 如果options中有router，说明是vue实例，而非组件
          _Vue.prototype.$router = this.$options.router;
        }
      },
    });
  }

  constructor(options) {
    this.options = options;
    // 配置默认路由
    const current = options.mode === HASH ? window.location.hash.slice(1) : window.location.pathname
    this.data = _Vue.observable({
      current: current || '/',
    });

    this.routerMap = {};

    // 初始化router
    this.init();
  }

  init () {
    this.createRouteMap();
    this.initComponent(_Vue);
    this.initEvent();
  }

  createRouteMap() {
    this.options.routes.forEach(router => {
      this.routerMap[router.path] = router.component;
    });
  }

  initComponent(Vue) {
    let self = this;
    // 注册全局组件router-link router-view
    Vue.component('router-link', {
      props: {
        to: String,
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to
          },
          on: {
            click: this.handleLinkClick
          },
        }, [this.$slots.default])
      },
      methods: {
        handleLinkClick(e) {
          // 阻止默认事件
          e.preventDefault();

          // 判断是hash模式还是history模式
          switch (self.options.mode) {
            case HASH:
              window.location.hash = this.to;
              break;
            case HISTORY:
            default:
              history.pushState({}, "", this.to);
              this.$router.data.current = this.to;
              break;
          }
        }
      }
    }) 
    Vue.component('router-view', {
      render(h) {
        return h(self.routerMap[self.data.current]);
      }
    })
  }

  initEvent() {
    if (this.options.mode === HASH) {
      window.addEventListener('hashchange', () => {
        this.data.current = window.location.hash.slice(1) || '/'
      })
    } else {
      window.addEventListener('popstate',() => {
        this.data.current = window.location.pathname
      })
    }
  }
}